import { defineStore } from 'pinia';
import { login } from '@/api/login.js';
import { setToken, setUsername } from '@/api/app.js';

export const loginStore = defineStore('loginStore', {
    // other options...
    state: ()=>{
        return {
            username: 'tst',
            token: ''
        }
    },
    getters: {

    },
    actions: {
        // 点击登录按钮后，发起登录请求，对应api文件api/login.js
        // 请求成功后，返回token
        login(loginUser){
            return login(loginUser).then((res)=>{
                const resp_data = res.data.data
                if(res.status == 200){
                    console.log("登录成功");
                    // 更新loginStore内username和token
                    this.username = resp_data.userName
                    this.token = resp_data.access_token

                    // 将username和token写入cookie
                    setUsername(resp_data.userName)
                    setToken(resp_data.access_token)

                    return Promise.resolve(res)
                }
            }).catch((error) => {
                console.log(error.response);
                return Promise.reject(error.response.data)
            })
        }
    }
  })
